package org.example;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.sftp.client.SftpClientFactory;
import org.apache.sshd.sftp.client.fs.SftpFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

/**
 * 远程部署应用程序并启动
 */
public class RemoteAutoDeploy {
	private static final Logger logger = LoggerFactory.getLogger(RemoteAutoDeploy.class);

	/**
	 * 远程部署
	 * @param sshIp
	 * @param sshPort
	 * @param sshUser
	 * @param connTimeout
	 * @param sshPassword
	 * @throws Exception
	 */
	public static void remoteDeploy(String sshIp, int sshPort, String sshUser, String sshPassword, long connTimeout) throws Exception {
		logger.info("SSH start remoteDeploy......");
		SshClient sshClient = null;
		ClientSession clientSession = null;
		try {
			try {
				sshClient = SshClient.setUpDefaultClient();
				sshClient.start();
				clientSession = sshClient.connect(sshUser, sshIp, sshPort).verify(connTimeout).getClientSession();
			} catch (Exception e) {
				logger.error("SSH connect host failed：", e);
				throw new Exception("ssh连接所在的主机异常");
			}
			logger.info("SSH connect with pwd......");
			try {
				//解密连接SSH
				clientSession.addPasswordIdentity(sshPassword);
				clientSession.auth().verify(connTimeout);
			} catch (Exception e) {
				logger.error("SSH auth failed,auth timeout/username or password error：", e);
				throw new Exception("ssh认证异常，认证超时/用户名或密码错误");
			}
			logger.info("SSH send file......");
			//1.发送文件
			SftpFileSystem sftpFileSystem = SftpClientFactory.instance().createSftpFileSystem(clientSession);
			String remoteDir = "/data/public";
			try {
				// 创建多层目录
				Path remote = sftpFileSystem.getDefaultDir().resolve(remoteDir);
				Files.createDirectories(remote);
				// 将目标文件拷贝至目标目录
				String localFile = "/home/localFile";
				Files.copy(Paths.get(localFile), remote.resolve("要远程发送的文件名称"), REPLACE_EXISTING);
			}catch (Exception e){
				logger.error("SSH send file failed：", e);
				throw new Exception("ssh发送文件失败");
			}
			logger.info("SSH start install......");
			try {
				//2.解压文件
				String unzipCmd = String.format("cd %s && tar -zxf 远程发送的文件名称",remoteDir);
				clientSession.executeRemoteCommand(unzipCmd);
				logger.info("SSH unzip finished......");
				//3.删除压缩包
				String delZipCmd = String.format("rm -f %s/远程发送的文件名称",remoteDir);
				clientSession.executeRemoteCommand(delZipCmd);
				logger.info("SSH delZipPackage finished......");
				//4.启动应用程序
				String startCmd =  String.format("cd %s/install && ./Start.sh > /dev/null 2>&1 &",remoteDir);
				clientSession.executeRemoteCommand(startCmd);
				logger.info("SSH install success");
			} catch (Exception e) {
				logger.error("SSH install failed：", e);
				throw new Exception("ssh安装失败");
			}
		} catch (Exception e) {
			throw new Exception(e);
		}  finally {
			if(clientSession != null) {
				clientSession.close();
			}
			if(sshClient != null) {
				sshClient.close();
			}
		}
	}
}